package com.gitee.mocoffee.json.spring;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import com.alibaba.fastjson.JSON;
import com.gitee.mocoffee.json.JsonKit;

/**
 * 该转换器用于将Controller中的@ResponseBody对象按照JSON格式输出
 *
 * @author lijia
 */
public class JsonHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
	private JsonHttpMessageConverter() {
		super(new MediaType("application", "json", StandardCharsets.UTF_8),
				new MediaType("application", "*+json", StandardCharsets.UTF_8));
	}

	public static final JsonHttpMessageConverter me = new JsonHttpMessageConverter();

	@Override
	protected boolean supports(Class<?> clazz) {
		return true;
	}

	@Override
	protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotReadableException {
		return JSON.parseObject(inputMessage.getBody(), StandardCharsets.UTF_8, Object.class);
	}

	@Override
	protected void writeInternal(Object o, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		String output = JsonKit.me.toJson(o);

		OutputStream out = outputMessage.getBody();
		byte[] bytes = output.getBytes(StandardCharsets.UTF_8);
		out.write(bytes);
		out.flush();
	}
}
